package com.qjs.shiro.test;

import java.lang.reflect.Array;
import java.util.Arrays;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.mgt.SecurityManager;
import org.junit.Test;

public class shiroBase1 {
	
	public Subject login(String username,String  password){
		SecurityManager sm=new IniSecurityManagerFactory("classpath:shiro.ini").getInstance();
		SecurityUtils.setSecurityManager(sm);
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken("zs", "123");
		try {
			subject.login(token);
			return subject;
		} catch (AuthenticationException e) {
			System.out.println("身份验证失败");
		}
		return null;
	}
	
	
	@Test
	public void testBase(){
			Subject subject=login("zs","123");
			PrincipalCollection ps=subject.getPrincipals();
			System.out.println(ps.toString());
			System.out.println(subject.getPrincipal());
	}
	
	@Test
	public void testRole(){
		Subject subject=login("zs","123");
		System.out.println(subject.hasRole("r1"));
		System.out.println(subject.hasAllRoles(Arrays.asList("r1","r4")));
		//返回boolean的数组集合
		System.out.println(subject.hasRoles(Arrays.asList("r1","r4")));
		//不存在，抛异常
		subject.checkRoles("r2");
	}
	
	@Test
	public void testPermission(){
		Subject subject=login("zs","123");
		System.out.println(subject.isPermitted("user:create"));
		System.out.println(subject.isPermitted("admin:view"));
	}
	
	@Test
	public void testMyPermission(){
		Subject subject=login("zs","123");
		System.out.println(subject.isPermitted("+user+create+*"));
		System.out.println(subject.isPermitted("classroom:*"));
	}
	
}
